package com.sourceQ.system.service.message.mail.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sourceQ.common.core.constant.message.MailSendStatusEnum;
import com.sourceQ.system.domain.message.mail.SysMailAccount;
import com.sourceQ.system.domain.message.mail.SysMailLog;
import com.sourceQ.system.domain.message.mail.SysMailTemplate;
import com.sourceQ.system.dto.message.MailLogPageReqDTO;
import com.sourceQ.system.mapper.message.mail.SysMailLogMapper;
import com.sourceQ.system.service.message.mail.SysMailLogService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.Objects;

import static cn.hutool.core.exceptions.ExceptionUtil.getRootCauseMessage;

/**
 * @author: SourceQ
 * @create: 2024-04-18 19:49
 * @Description:
 */
@Service
public class SysMailLogServiceImpl extends ServiceImpl<SysMailLogMapper, SysMailLog> implements SysMailLogService {
    @Override
    public IPage<SysMailLog> getMailLogPage(Page page, MailLogPageReqDTO pageReqDTO) {
        return baseMapper.getMailLogPage(page,pageReqDTO);
    }

    @Override
    public SysMailLog getMailLog(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    public Long createMailLog(Long userId, Integer userType, String toMail, SysMailAccount account, SysMailTemplate template, String templateContent, Map<String, Object> templateParams, Boolean isSend) {
        SysMailLog mailLog = SysMailLog.builder().sendStatus(Objects.equals(isSend, true) ? MailSendStatusEnum.INIT.getStatus()
                        : MailSendStatusEnum.IGNORE.getStatus())
                // 用户信息
                .userId(userId).userType(userType).toMail(toMail)
                .accountId(account.getId()).fromMail(account.getMail())
                // 模板相关字段
                .templateId(template.getId()).templateCode(template.getCode()).templateNickname(template.getNickname())
                .templateTitle(template.getTitle()).templateContent(templateContent).templateParams(templateParams).build();
        baseMapper.insert(mailLog);
        return mailLog.getId();
    }

    @Override
    public void updateMailSendResult(Long logId, String messageId, Exception exception) {
        // 1. 成功
        if (exception == null) {
            baseMapper.updateById(new SysMailLog().setId(logId).setSendTime(LocalDateTime.now())
                    .setSendStatus(MailSendStatusEnum.SUCCESS.getStatus()).setSendMessageId(messageId));
            return;
        }
        // 2. 失败
        baseMapper.updateById(new SysMailLog().setId(logId).setSendTime(LocalDateTime.now())
                .setSendStatus(MailSendStatusEnum.FAILURE.getStatus()).setSendException(getRootCauseMessage(exception)));
    }
}
